package net.java.aioechotest;

import net.java.nioserver.utils.ChannelUtil;

import java.nio.channels.SocketChannel;
import java.nio.ByteBuffer;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

/**
 * @author Leonid Shlyapnikov
 */
public class OpReadEchoTask implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(OpReadEchoTask.class);

    private SocketChannel sc;

    public OpReadEchoTask(SocketChannel sc) {
        this.sc = sc;
    }

    public void run() {
        ByteBuffer echoBuffer = ByteBuffer.allocate(20);

        boolean runMore = true;
        try {
            runMore = ChannelUtil.readFromChannel(sc, echoBuffer);
            echoBuffer.flip();
            ChannelUtil.writeToChannel(echoBuffer, sc);
        } catch (Exception e) {
            log.error("Cannot finish task: " + this, e);
        } finally {
            if (!runMore) {
                log.info("Closing " + this);
                ChannelUtil.close(sc);
            }
        }
    }

    public String toString() {
        return this.getClass().getSimpleName() + "{" +
                "sc=" + sc +
                '}';
    }
}